<template>
  <div class="team-review-container">
    <a-spin :spinning="loading">
      <!-- 空状态 -->
      <a-empty
        v-if="!loading && filteredTeams.length === 0"
        :description="noTeamText"
        class="empty-tip"
      />

      <!-- 战队标签页 -->
      <a-tabs v-model:activeKey="activeTeamId" @change="handleTeamChange" v-else>
        <a-tab-pane 
          v-for="team in filteredTeams" 
          :key="team.id"
        >
          <!-- 自定义标签内容 -->
          <template #tab>
            <span class="custom-tab">
              <span class="team-name">{{ team.teamName }}</span>
              <a-badge 
                v-if="activeTeamId === team.id && pendingMembers.length > 0"
                :count="pendingMembers.length" 
                :number-style="{ backgroundColor: '#52c41a' }"
              />
            </span>
          </template>

          <!-- 成员审核区域 -->
          <div class="member-review-section">
            <div class="section-header">
              <h3>待审核成员 ({{ pendingMembers.length }})</h3>
              <a-button type="primary" @click="fetchPendingMembers" :loading="memberLoading">
                <template #icon><reload-outlined /></template>
                刷新
              </a-button>
            </div>

            <a-spin :spinning="memberLoading">
              <a-empty
                v-if="pendingMembers.length === 0"
                description="暂无待审核成员"
                class="empty-tip"
              />

              <a-list
                v-else
                :data-source="pendingMembers"
                bordered
                item-layout="horizontal"
              >
                <template #renderItem="{ item }">
                  <a-list-item class="member-item">
                    <a-list-item-meta>
                      <template #title>
                        <div class="member-title">
                          <a-avatar :src="item.filePath || '/default-avatar.png'" />
                          <span class="username">{{ item.username }}</span>
                          <a-tag color="orange">待审核</a-tag>
                        </div>
                      </template>
                      <template #description>
                        <div class="member-info">
                          <div><span class="label">用户ID:</span> {{ item.userId }}</div>
                          <div><span class="label">申请时间:</span> {{ formatDate(item.joinTime) }}</div>
                          <div v-if="item.inviterName"><span class="label">邀请人:</span> {{ item.inviterName }}</div>
                        </div>
                      </template>
                    </a-list-item-meta>

                    <template #actions>
                      <a-space>
                        <a-button 
                          type="primary" 
                          @click="handleReview(item, 0)"
                          :loading="reviewLoading[item.userId]?.approve"
                        >
                          通过
                        </a-button>
                        <a-button 
                          danger 
                          @click="handleReview(item, 2)"
                          :loading="reviewLoading[item.userId]?.reject"
                        >
                          拒绝
                        </a-button>
                      </a-space>
                    </template>
                  </a-list-item>
                </template>
              </a-list>
            </a-spin>
          </div>
        </a-tab-pane>
      </a-tabs>
    </a-spin>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { message, Modal } from 'ant-design-vue';
import { ReloadOutlined } from '@ant-design/icons-vue';
import { findMyTeams, getReviewMembers, reviewMember } from '@/api/sysTeamController';
import dayjs from 'dayjs';

// 数据状态
const myTeams = ref([]);
const activeTeamId = ref(null);
const pendingMembers = ref([]);
const loading = ref(false);
const memberLoading = ref(false);
const reviewLoading = ref({});

// 计算属性
const filteredTeams = computed(() => {
  return myTeams.value.filter(team => team.needReview === 1);
});

const noTeamText = computed(() => {
  return myTeams.value.length === 0 
    ? '您不是任何战队的队长，没有管理权限' 
    : '没有需要审核的战队';
});

// 格式化日期
const formatDate = (date) => {
  return date ? dayjs(date).format('YYYY-MM-DD HH:mm') : '未知时间';
};

// 获取我是队长的战队列表
const fetchMyTeams = async () => {
  try {
    loading.value = true;
    const { data: res } = await findMyTeams();
    
    if (res?.code === 0) {
      myTeams.value = res.data || [];
      
      // 默认选中第一个需要审核的战队
      if (filteredTeams.value.length > 0) {
        activeTeamId.value = filteredTeams.value[0].id;
        await fetchPendingMembers();
      }
    } else {
      message.error(res?.message || '获取战队列表失败');
    }
  } catch (error) {
    console.error('获取战队列表失败:', error);
    message.error('获取战队列表失败，请检查网络');
  } finally {
    loading.value = false;
  }
};

// 获取待审核成员
const fetchPendingMembers = async () => {
  if (!activeTeamId.value) return;
  
  try {
    memberLoading.value = true;
    const { data: res } = await getReviewMembers({ teamId: activeTeamId.value });
    
    if (res?.code === 0) {
      pendingMembers.value = res.data?.filter(member => member?.status === 1) || [];
    } else {
      message.error(res?.message || '获取成员列表失败');
    }
  } catch (error) {
    console.error('获取成员列表失败:', error);
    message.error('获取成员列表失败，请稍后重试');
  } finally {
    memberLoading.value = false;
  }
};

// 切换战队
const handleTeamChange = (teamId) => {
  activeTeamId.value = teamId;
  fetchPendingMembers();
};

// 审核成员
const handleReview = async (member, status) => {
  Modal.confirm({
    title: `确认${status === 0 ? '通过' : '拒绝'}申请?`,
    content: `确定要${status === 0 ? '通过' : '拒绝'} ${member.username} 的入队申请吗?`,
    onOk: async () => {
      try {
        reviewLoading.value = {
          ...reviewLoading.value,
          [member.userId]: { [status === 0 ? 'approve' : 'reject']: true }
        };
        
        const { data: res } = await reviewMember({
          teamId: activeTeamId.value,
          memberId: member.userId,
          status
        });
        
        if (res?.code === 0) {
          message.success(`已${status === 0 ? '通过' : '拒绝'}申请`);
          await fetchPendingMembers();
        } else {
          message.error(res?.message || '操作失败');
        }
      } catch (error) {
        console.error('审核操作失败:', error);
        message.error('操作失败，请稍后重试');
      } finally {
        reviewLoading.value = {
          ...reviewLoading.value,
          [member.userId]: { [status === 0 ? 'approve' : 'reject']: false }
        };
      }
    }
  });
};

// 初始化加载
onMounted(() => {
  fetchMyTeams();
});
</script>

<style scoped>
.team-review-container {
  padding: 24px;
  min-height: calc(100vh - 48px);
}

.custom-tab {
  display: inline-flex;
  align-items: center;
  gap: 8px;
}

.team-name {
  margin-right: 4px;
}

.member-review-section {
  background: #fff;
  padding: 24px;
  border-radius: 8px;
  margin-top: 16px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.member-item {
  padding: 16px;
  transition: all 0.2s;
}

.member-item:hover {
  background: #fafafa;
}

.member-title {
  display: flex;
  align-items: center;
  gap: 12px;
}

.member-info {
  display: flex;
  flex-direction: column;
  gap: 6px;
  font-size: 13px;
}

.label {
  color: rgba(0, 0, 0, 0.45);
  margin-right: 8px;
  display: inline-block;
  min-width: 60px;
  text-align: right;
}

.empty-tip {
  margin: 40px 0;
  padding: 40px 0;
  background: #fff;
  border-radius: 8px;
}
</style>